package com.rlax.framework.support.openapi;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 参数签名
 * 
 * @author Rlax
 * 
 */
public class ParamSign {

	public static final String SIGN_TAG = "_sign";
	public static final String APPID_TAG = "_appid";
	public static final String TIMESTAMP_TAG = "_timestamp";
	
	/**
	 * 签名
	 * @param paramMap 参数
	 * @param appkey appKey
	 * @param secret secret
	 * @return
	 */
	public static String sign(Map<String, String> paramMap, String appkey,
			String secret) {
		// 对参数名进行字典排序
		String[] keyArray = paramMap.keySet().toArray(new String[0]);
		Arrays.sort(keyArray);

		// 拼接有序的参数名-值串
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(appkey);
		for (String key : keyArray) {
			stringBuilder.append(key).append(paramMap.get(key));
		}

		stringBuilder.append(secret);
		String codes = stringBuilder.toString();
		System.out.println(codes);
		// 字符串连接示例
		// XXXXXXXXcategory美食city上海formatjsonhas_coupon1has_deal1keyword泰国菜latitude31.21524limit20longitude121.420033offset_type0radius2000region长宁区sort7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

		// SHA-1编码， 这里使用的是Apache
		// codec，即可获得签名(shaHex()会首先将中文转换为UTF8编码然后进行sha1计算，使用其他的工具包请注意UTF8编码转换)
		/*
		 * 以下sha1签名代码效果等同 byte[] sha =
		 * org.apache.commons.codec.digest.DigestUtils
		 * .sha(org.apache.commons.codec
		 * .binary.StringUtils.getBytesUtf8(codes)); String sign =
		 * org.apache.commons
		 * .codec.binary.Hex.encodeHexString(sha).toUpperCase();
		 */
		String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes)
				.toUpperCase();
		return sign;
	}

	public static void main(String[] args) {
		// 定义申请获得的appKey和appSecret
		String appkey = "yunxinkey";
		String secret = "yunxinsecret";

		// 创建参数表
		Map<String, String> paramMap = new HashMap<String, String>();
//		paramMap.put("custName", "云链账号");
//		paramMap.put("orgCode", "18335187915");
//		paramMap.put("custId", "C10000129");
		
		paramMap.put("wid", "W20160907-000062");
		
		paramMap.put("loginType", "YS");
		paramMap.put("_appid", "3");
		paramMap.put("_timestamp", "1473748923000");

		String sign = sign(paramMap, appkey, secret);
		
		// 将签名加入请求参数
		paramMap.put("_sign", sign);
		System.out.println(sign);
	}
}
